package cn.iocoder.yudao.module.system.dal.mysql.answerRecord;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.system.controller.admin.answerRecord.vo.AnswerRecordPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.answerRecord.AnswerRecordDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.util.Assert;

/**
 * 用户回答记录 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface AnswerRecordMapper extends BaseMapperX<AnswerRecordDO> {

    default PageResult<AnswerRecordDO> selectPage(AnswerRecordPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<AnswerRecordDO>()
                .eqIfPresent(AnswerRecordDO::getUserId, reqVO.getUserId())
                .eqIfPresent(AnswerRecordDO::getLastAnswerQuestionId, reqVO.getLastAnswerQuestionId())
                .eqIfPresent(AnswerRecordDO::getAnswerNo, reqVO.getAnswerNo())
                .eqIfPresent(AnswerRecordDO::getStatus, reqVO.getStatus())
                .betweenIfPresent(AnswerRecordDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(AnswerRecordDO::getId));
    }

    /**
     * 原子操作：更新报告数量（增加）和状态
     *
     * @param id     记录编号
     * @param status 要设置的状态
     * @param reportName 报告名称，如果为null则不更新
     * @return 更新的行数
     */
    default int updateReportCountIncrAndStatus(Integer id, Integer status, String reportName) {
        LambdaUpdateWrapper<AnswerRecordDO> updateWrapper = new LambdaUpdateWrapper<AnswerRecordDO>()
                .eq(AnswerRecordDO::getId, id)
                .set(AnswerRecordDO::getStatus, status)
                .setSql("report_count = IFNULL(report_count, 0) + 1");

        // 如果报告名称不为空，则更新报告名称
        if (reportName != null) {
            updateWrapper.set(AnswerRecordDO::getReportName, reportName);
        }

        return update(null, updateWrapper);
    }

}